import React, {memo, ReactNode, useEffect, useState} from 'react'
import { Form, Input, Checkbox, Button, VerificationCode, Message } from '@arco-design/web-react';
import { IconUser, IconLock, IconSend } from '@arco-design/web-react/icon';
import { getUserLogin } from '@/apis/demo';
interface IProps {
  children?: ReactNode
  onSubmit?: () => void
  onOk?: () => void
  onCancel?: () => void
  onSussess?: () => void
}
const FormItem = Form.Item;

function Login(props:IProps) {
  const [mode, setMode] = useState(true)
  return (
    <div className={'w-full h-80 flex'}>
      {/* 二维码扫描 */}
      <div className={'w-1/2 border-r flex flex-col justify-center items-center border-box px-4 cursor-default'}>
        <div className={'px-3 py-1 mt-2 bg-pink-400 rounded-xl text-center font-bold text-white'}>
          登录后推荐更懂你的音乐
        </div>
        <div className={'bg-primary-600 text-white w-16 text-center rounded-full my-2'}>Ruim</div>
        <div className={"flex-1 w-full flex justify-center items-center"}>
          <img width={'150'} height={'150'} src={"./二维码demo.png"} alt='...'/>
        </div>
        <div className={'h-[1.5em] mt-2 text-xs text-gray-300'}>▶期待你的加入</div>
      </div>
      {/* 登录 */}
      <div className={"w-1/2 flex flex-col justify-center items-center px-4 select-none"}>
        <p className={"font-bold mb-4"}>账号密码登录</p>
        <div className={"w-full flex-1 p-2 flex justify-center items-center"}>
          {mode?<LoginFormUser onSubmit={props.onSussess}></LoginFormUser>:<RegisterFormPhone onSubmit={()=>setMode(!mode)}></RegisterFormPhone>}
        </div>
        <div className={"text-gray-300  flex justify-between text-xs w-full "}>
          <span className={"cursor-pointer"} onClick={()=>setMode(!mode)}>{mode?'注册账号':'前往登录'}</span>
          <span className={"cursor-pointer"}>忘记密码？</span>
          <span className={"cursor-pointer"}>更多登录方式</span>
        </div>
      </div>
    </div>
  )
}
export default memo(Login)

//电话正则  可以为1-11位有效的手机号，以1开头，第二位可以为3-9，后面为数字
const phoneRegex = /^1[3-9]\d{9}$/;
// 账号正则
const accountRegex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d_]{6,20}$/;
// 密码正则
const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d._]{8,32}$/;

function LoginFormUser(props:IProps) {
  const [form] = Form.useForm();
  return (
    <Form
      form={form}
      autoComplete='off'
      className={" pl-4"}
      validateMessages={{
        required: (_, { label }) => `必须填写 ${label || ''}`,
        string: {
          length: `字符数必须是 #{length}`,
          match: `不匹配正则`,
        },
      }}
    >
      <FormItem
        field='username'
        rules={[
            {
              type: 'string',
              required: true,
              match: phoneRegex,
            },
          ]}
        >
        <Input
          style={{width:"240px"}}
          prefix={<IconUser />}
          autoComplete='current-password'
          placeholder='请输入你的账号...'
        />
      </FormItem>
      <FormItem field='password'  rules={[
        {
          type: 'string',
          required: true,
          match: passwordRegex,
        },
      ]}>
        <Input.Password style={{width:"240px"}} autoComplete='current-password' prefix={<IconLock />} placeholder='请输入密码...' />
      </FormItem>
      <Button onClick={() => {
        form.validate().then(values => {
          if(values['remember']){
            console.log(values)
            getUserLogin(values).then(res => {
              if(res.code === 200){
                Message.success('登录成功');
                localStorage.setItem('token', JSON.stringify(res.data));
                if (typeof props.onSubmit === 'function') {
                  props.onSubmit();
                }

              }else{
                Message.error('账号或密码错误');
              }
            })
          }else{
            Message.warning('请阅读用户协议和隐私政策')
          }
        }).catch(() => {
          Message.error('请检查输入是否正确');
        });
      }}  className={"mb-2"} style={{background: "#8b96d9",width:"240px"}} long type='primary'>登 录</Button>
      <FormItem field={'remember'} className={""}>
        <Checkbox onChange={(e) => {form.setFieldsValue({ remember: e })}} style={{width:"240px"}}><span className="text-gray-300 font-light text-xs">我已阅读<span className={"text-primary-600"}>《用户协议》</span><span className={"text-primary-600"}>《隐私政策》</span></span></Checkbox>
      </FormItem>
    </Form>
  )
}

function RegisterFormPhone(props:IProps) {
  const [form] = Form.useForm();
  // 发送验证码倒计时
  const [timeLeft, setTimeLeft] = useState(0);
  const [isCounting, setIsCounting] = useState(false);

  // Handle button click to start the countdown
  const handleClick = () => {
    if (!isCounting) {
      // Set the initial time to 60 seconds
      setTimeLeft(60);
      setIsCounting(true);
    }
  };

  // Use effect for handling the countdown logic
  useEffect(() => {
    let intervalId:any;

    if (isCounting && timeLeft > 0) {
      intervalId = setInterval(() => {
        setTimeLeft(prevTime => prevTime - 1);
      }, 1000);
    } else if (timeLeft === 0) {
      setIsCounting(false);
      clearInterval(intervalId); // Clear the interval when it reaches zero
    }

    // Cleanup function to clear the interval on component unmount or state change
    return () => clearInterval(intervalId);
  }, [isCounting, timeLeft]);

  return (
    <Form form={form} autoComplete='off' className={"pl-4"}>
      <FormItem label='' required field='phone' rules={[
        {
          validator(value, cb) {
            if (!phoneRegex.test(value)) {
              return cb('请输入正确的手机号码');
            }
            return cb();
          },
        },
      ]}>
        <Input
          style={{width:"240px", margin: 0}}
          prefix={"+86"}
          addAfter={
            isCounting  ? (
              <span className={'text-gray-400'} style={{width: '3em'}}>{timeLeft}s</span>
            ) : (
            <Button
              type='text'
              style={{color: '#8b96d9'}}
              onClick={() => {
                //  获取form表单数据
                console.log(form.getFieldsValue());
                // 确认电话号码格式正确后发送验证码
                form.validate().then(values => {
                  if(values['phone']){
                    Message.success('验证码已发送，请注意查收');
                    // 发送验证码倒计时
                    handleClick();
                  }else{
                    Message.error('请输手机号码')
                  }
                }).catch(() => {
                  Message.clear();
                  Message.error('请输入正确的手机号码')
                })

              }}><IconSend color='#8b96d9'/></Button>
            )
          }
          autoComplete='off'
          placeholder='请输入你的手机...'
          normalizeTrigger={['onBlur']}
          normalize={v => !phoneRegex.test(v) ? "" : v}
        />
      </FormItem>
      <FormItem label='' required field='verificationCode'>
        <VerificationCode
          style={{width: 240}}
          onFinish={v => {
            form.setFieldsValue({ verificationCode: v })
          }}
        />
      </FormItem>
      <Button onClick={() => {
        form.validate().then(values => {
          if(!values['verificationCode']){
            Message.warning('请输入验证码');
            return;
          }
          if(values['verificationCode'] && values['remember']){
            console.log(values)
            Message.success('注册成功，请登录');
            if (typeof props.onSubmit === 'function') {
              props.onSubmit();
            }
          }else{
            Message.warning('请阅读用户协议和隐私政策')
          }
        }).catch(() => {
          Message.error('请检查输入是否正确');
        });
      }} className={"mb-2"} style={{background: "#8b96d9",width:"240px"}} long type='primary'>注 册</Button>
      <FormItem field={'remember'} className={""}>
        <Checkbox style={{width:"240px"}}><span className="text-gray-300 font-light text-xs">我已阅读<span className={"text-primary-600"}>《用户协议》</span><span className={"text-primary-600"}>《隐私政策》</span></span></Checkbox>
      </FormItem>
    </Form>
  )
}


